//
//  CouseFeedbackViewController.swift
//  ddx0513
//
//  Created by ejian  on 15/6/16.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

class CourseFeedbackViewController: UITableViewController, UITextViewDelegate {
    var textPlacehold = true
    var starRateView: CWStarRateView?
    var score: CGFloat = 1.0
    var numOfstarScore:Int = 0
    var lessonId:Int!
    var delegate: PopupDelegate?
    var hud: MBProgressHUD?
    @IBOutlet weak var textView: UITextView!
    

    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        self.starRateView = CWStarRateView(frame: CGRectMake(80, 10, 100, 21), numberOfStars: 5)
        self.starRateView?.scorePercent = score
//        println(self.starRateView?.starScore)
        self.starRateView!.allowIncompleteStar = false
        self.starRateView!.hasAnimation = true
        self.view.addSubview(self.starRateView!)
        
        
        textView.layer.borderColor = UIColor.lightGrayColor().CGColor
        textView.layer.borderWidth = 0.5
//        textView.layer.cornerRadius = 6
//        textView.layer.masksToBounds = true
        textView.text = "还可以写100字以内的评论哦"
        textView.textColor = UIColor.darkGrayColor()
    }
    
    func submitData()
    {
        numOfstarScore = Int(self.starRateView!.starScore)
        startIndicator()
        
        var s = self.textView.text
        if (textPlacehold) {
            s = ""
        }
        let a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token,"lessonid": lessonId, "star": numOfstarScore , "context": s]
        
        //NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLAddComment(), parameters: (a as! [String : AnyObject]), view: self.view, responseHandler: stopIndicator, successHandler: save)
        NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLAddComment(), parameters: (a as! [String : AnyObject]), view: self.view, responseHandler: stopIndicator, successHandler: save)
    }
    
    @IBAction func judgeCommit(sender: AnyObject) {
        submitData()
        
    }
    
    //MARK: - 网络回调函数
    
    func startIndicator() {
        hud = MBProgressHUD(view: self.view)
        self.view.addSubview(hud!)
        hud?.labelText = "提交中.."
        hud?.show(true)
    }
    
    func stopIndicator() {
        hud?.hide(false)
    }
    
    func save(json: JSON) {
        hud!.mode = MBProgressHUDMode.Text
        hud!.labelText = "提交成功"
        hud!.margin = 10.0
        hud!.removeFromSuperViewOnHide = true
        hud!.square = true
        
        hud?.showWhileExecuting(Selector("save2"), onTarget: self, withObject: nil, animated: true)
    }
    
    func save2() {
        sleep(1)
        
        self.delegate?.dismissPopup(true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func ExitButtonPressed(sender: AnyObject) {
        self.delegate?.dismissPopup(true)
    }
    
    func textViewDidBeginEditing(textView: UITextView) {
        if (textPlacehold) {
            textPlacehold = false
            textView.text = ""
            textView.textColor = UIColor.blackColor()
        }
    }
    
    func textViewDidEndEditing(textView: UITextView) {
        if (!textPlacehold && count(textView.text) == 0) {
            textPlacehold = true
            textView.text = "还可以写100字以内的评论哦"
            textView.textColor = UIColor.darkGrayColor()
        }
    }
    
    func textViewDidChange(textView: UITextView) {
        var str = textView.text
        var num = count(str)
        if (num > 100) {
            let range = Range(start: str.startIndex, end: advance(str.startIndex, 100))
            self.textView.text = str.substringWithRange(range)
        }
    }

    /*func textFieldShouldReturn(textField: UITextField!) -> Bool{
        textView.delegate = self
        textView.resignFirstResponder()
        return true
    }*/
    

    // MARK: - Table view data source

//    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//        // #warning Potentially incomplete method implementation.
//        // Return the number of sections.
//        return 0
//    }
//
//    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        // #warning Incomplete method implementation.
//        // Return the number of rows in the section.
//        return 0
//    }

    /*
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell

        // Configure the cell...

        return cell
    }
    */
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch (indexPath.row) {
        case 1:
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            self.delegate?.dismissPopup(true)
        default:
            return
        }
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
